import { createRouter, createWebHistory } from 'vue-router'
import MainLayout from '../layout/MainLayout.vue'

const routes = [
  {
    path: '/',
    component: MainLayout,
    children: [
      {
        path: '',
        name: 'Dashboard',
        component: () => import('../views/Dashboard.vue'),
        meta: { requiresAuth: true }
      },
      {
        path: 'wrong-questions',
        name: 'WrongQuestions',
        component: () => import('../views/WrongQuestions.vue'),
        meta: { requiresAuth: true }
      },
      {
        path: 'community',
        name: 'Community',
        component: () => import('../views/Community.vue'),
        meta: { requiresAuth: true }
      },
      {
        path: 'qa',
        name: 'QA',
        component: () => import('../views/QA.vue'),
        meta: { requiresAuth: true }
      }
    ]
  },
  {
    path: '/login',
    name: 'Login',
    component: () => import('../views/Login.vue'),
  },
  {
    path: '/register',
    name: 'Register',
    component: () => import('../views/Register.vue'),
  },
  // 将通配符路由放在最后
  {
    path: '/:pathMatch(.*)*',
    redirect: '/login'
  },
  {
    path: '/documents',
    name: 'DocumentList',
    component: () => import('../views/DocumentList.vue'),
    meta: { requiresAuth: true }
  },
  {
    path: '/documents/:id/qa',
    name: 'DocumentQA',
    component: () => import('../views/DocumentQA.vue'),
    meta: { requiresAuth: true }
  },
  {
    path: '/my-likes',
    name: 'MyLikes',
    component: () => import('../views/MyLikes.vue'),
    meta: {
      requiresAuth: true
    }
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes
})

// 简化路由守卫逻辑
router.beforeEach((to, from, next) => {
  console.log('Navigating to:', to.path)
  const token = localStorage.getItem('token')
  
  if (to.matched.some(record => record.meta.requiresAuth) && !token) {
    next('/login')
  } else if (token && to.path === '/login') {
    next(from.path)
  } else {
    next()
  }
})

export default router 